import React, { PureComponent } from 'react'
import { StyleSheet, View, Text } from 'react-native'
import { WhiteSpace } from 'antd-mobile'
import {connect} from 'react-redux'
import Spinner from 'react-native-loading-spinner-overlay'
import screen from '../../utils/screen'
import { createAction, NavigationActions } from '../../utils'
import { Summary,OwnCard, ButtonGroup, LineChart, PullView, ViewMoreText } from '../../widgets'


const buttons = ['营业收入', '营业成本', '营业利润']
const twoButtons = ['利润总额', '净利润']

@connect(({ home,profit, loading }) => ({ ...home, ...profit, isLoading: loading.models.profit }))
export default class extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      idx: 0
    }
  }

  componentDidMount() {
    const mainTime= this.props.mainTime;
    this.loadContent(mainTime.startTime, mainTime.endTime)
  }

  componentWillReceiveProps(nextProps) {
    const mainTime= this.props.mainTime;
    const nextMainTime = nextProps.mainTime;
    console.log('profit receive props.')
    if(nextMainTime.startTime === undefined || nextMainTime.endTime === undefined) {
      return false
    }
    if(nextMainTime.startTime !== mainTime.startTime || nextMainTime.endTime !== mainTime.endTime) {
      this.loadContent(nextMainTime.startTime, nextMainTime.endTime)
    }
  }

  loadContent = (startT, endT) => {
    console.log('profit load content .')
    this.props.dispatch(createAction("profit/getProfitMainMsg")({
      startTime: startT,
      endTime: endT
    }))
    this.props.dispatch(createAction("profit/getContentMsg")({
      startTime: startT,
      endTime: endT
    }))
    this.props.dispatch(createAction("profit/getProfitCompare")({
      startTime: startT,
      endTime: endT,
      useArea: this.getUseArea()
    }))
  }

  getUseArea = () => {
    const idx = this.state.idx
    let useArea = 0
    if(idx === 0) {
      useArea = 21
    } else if(idx === 1) {
      useArea = 22
    } else if(idx === 2) {
      useArea = 23
    } else if(idx === 3) {
      useArea = 24
    } else if(idx === 4) {
      useArea = 25
    }
    return useArea
  }

  getCompareParams = () => {
    const mainTime= this.props.mainTime;
    const params = {
      startTime: mainTime.startTime,
      endTime: mainTime.endTime,
      useArea: this.getUseArea()
    }
    return params
  }

  changeIdx = (idx) => {
    this.setState({
      idx: idx
    },() => {
      this.props.dispatch(createAction("profit/getProfitCompare")(this.getCompareParams()))
    })
  }

  geneProfitSummary = (profitSummary) => {
    const yysr = profitSummary.yysr || {}
    const yycb = profitSummary.yycb || {}
    const yylr = profitSummary.yylr || {}
    const lrze = profitSummary.lrze ||{}
    const jlr = profitSummary.jlr || {}
    return [{
      zi: '营业收入',
      chou: (yysr.onRise || 0),
      yin: yysr.showMoney || 0
    },{
      zi: '营业成本',
      chou: (yycb.onRise || 0),
      yin: yycb.showMoney || 0
    },{
      zi: '营业利润',
      chou: (yylr.onRise || 0),
      yin: yylr.showMoney || 0
    },{
      zi: '利润总额',
      chou: (lrze.onRise || 0),
      yin: lrze.showMoney || 0
    },{
      zi: '净利润',
      chou: (jlr.onRise || 0 ),
      yin: jlr.showMoney || 0
    }]
  }

  renderChartOptions = (text, legends, xAxisDatas, datas) => {
    const option = {
      title : {
        show: false,
        text: text,
      },
      tooltip : {
        trigger: 'axis',
        formatter: function(datas, ticket, callback) {
          const axisDatas = datas[0].name || {}
          let res = axisDatas.time + '<br/>', val;
          for(var i = 0, length = datas.length; i < length; i++) {
            val = datas[i].value;
            res += datas[i].seriesName + '：' + val + '<br/>';
          }
          res += "同比：" + axisDatas.tb + "%" + '<br/>'
          res += "环比：" + axisDatas.hb + "%" +  '<br />'
          return res;
        }
      },
      grid: {
        containLabel: true
      },
      legend: {
        bottom: 'bottom',
        data: legends
      },
      xAxis : [
        {
          type : 'category',
          top: 'bottom',
          data : xAxisDatas,
          axisLabel: {
            formatter: function(value = {}, idx) {
              return value.time || ""
            }
          }
        }
      ],
      yAxis : [
        {
          type : 'value',
          name: '金额(万元)'
        }
      ],
      series : [
        {
          name: legends[0],
          type:'line',
          data: datas[0],
        },
        {
          name: legends[1],
          type:'line',
          data: datas[1],
        }
      ]
    };
    return option
  }

  render() {
    const { idx } = this.state
    const { profitSummary,isLoading,mainTime, lineXX, lineYysr, lineYycb, lineYylr, lineLrze, lineJlr, yj, gy } = this.props;
    const times = profitSummary.times
    const summaryD = this.geneProfitSummary(profitSummary)
    const legends = ['本期', '上期']
    const lineXXOptions = this.renderChartOptions('', legends, lineXX.xAxisDatas, lineXX.lineDatas)
    return (
      <PullView onPullRelease={() => {
        this.loadContent(mainTime.startTime, mainTime.endTime)
      }}>
        <Spinner visible={isLoading} />
        <View style={styles.summary}>
          <Summary onCellPress={() =>{
            this.props.navigation.navigate('ProfitStack',{
              initTime: mainTime
            })
          }} content={summaryD} times={times}/>
        </View>
        <WhiteSpace />
        <OwnCard title="概述" extra="报表明细" extraOnPress={() => {
          this.props.navigation.navigate('ProfitStack',{
            initTime: mainTime
          })
        }}>
          <ViewMoreText>{gy}</ViewMoreText>
        </OwnCard>
        <WhiteSpace/>
        <OwnCard title="预警" extraOnPress={() => {}}>
          <ViewMoreText>{yj}</ViewMoreText>
        </OwnCard>
        <WhiteSpace/>
        <OwnCard title="主要指标变动趋势">
          <ButtonGroup
            onPress={(idx) => this.changeIdx(0 + idx)}
            selectedIndex={idx}
            buttons={buttons}
          />
          <ButtonGroup
            onPress={(idx) => this.changeIdx(3 + idx)}
            selectedIndex={idx - 3 }
            buttons={twoButtons}
          />
          <LineChart options={lineXXOptions}/>
        </OwnCard>
      </PullView>
    )
  }
}


const styles = StyleSheet.create({
  summary: {
    paddingHorizontal: screen.pxToDp(26),
    backgroundColor: 'white',
    flex: 1,
  },
})
